﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class VendorButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
    [SerializeField]
    private Image icon;
    [SerializeField]
    private Text title;
    [SerializeField]
    private Text qty;
    [SerializeField]
    private Text price;
    private VendorItem vendorItem;
    public void OnPointerClick(PointerEventData eventData)
    {
        if (Player.MyInstance.MyGold >= vendorItem.MyItem.MyPrice && inventoryScript.MyInstance.AddItem(Instantiate(vendorItem.MyItem)))
        {
            Sell();
            
        }
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        UIManager.MyInstance.showToolTip(new Vector2(0,1),transform.position,vendorItem.MyItem);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        UIManager.MyInstance.hideToolTip(); 
    }
    public void AddItem(VendorItem item)
    {

        this.vendorItem = item;
        if(item.MyQty>0|| item.MyUnlimited)
        {
            if (item.MyItem.MyPrice > 0)
            {
                price.text = item.MyItem.MyPrice.ToString() + " G";
            }
            icon.sprite = item.MyItem.Icon;
            title.text = string.Format("<color={0}>{1}</color>", ItemRarityColor.MyRarityColours[item.MyItem.MyItemRarity], item.MyItem.MyTitle);
            if (!item.MyUnlimited)
            {
                qty.text = item.MyQty.ToString();
            }
            else
            {
                qty.text = string.Empty;
            }
            gameObject.SetActive(true);
        }

    }
    private void Sell()
    {
        Player.MyInstance.MyGold -= vendorItem.MyItem.MyPrice;
        if(!vendorItem.MyUnlimited)
        {
            vendorItem.MyQty--;
            qty.text = vendorItem.MyQty.ToString();
            if (vendorItem.MyQty == 0)
            {
                gameObject.SetActive(false);
            }
        }
    }

}
